package com.google.project.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.project.client.Service.UploadService;
import com.google.project.server.entity.Document;
import com.google.project.shared.DocumentDTO;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class UploadServiceImpl extends RemoteServiceServlet implements
		UploadService {

	private BlobstoreService blobstoreService = BlobstoreServiceFactory
	.getBlobstoreService();
	
	@Override
	public String getBlobStoreUrl() {
		String url = blobstoreService.createUploadUrl("/upload");
		return url;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DocumentDTO> getBlobs(String forID, String dataType) {
		List<DocumentDTO> listDoc = new ArrayList<DocumentDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Document.class);
		q.setFilter("forId == forID && type == dataType");
		q.declareParameters("String forID, String dataType");
		try {
			List<Document> list = (List<Document>) q.execute(forID, dataType);
			for (Document doc : list) {
				listDoc.add(doc.toDTO());
			}
		} catch (Exception e) {
		} finally {
			pm.close();
		}
		return listDoc;
	}

	public boolean deleteDoc(String key) {
		if (key == null) {
			return false;
		}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Document c = pm.getObjectById(Document.class, key);
			BlobKey blobKeys = new BlobKey(c.getBlobKey());
			blobstoreService.delete(blobKeys);
			pm.deletePersistent(c);
		} finally {
			pm.close();
		}
		return true;
	}

	@Override
	public boolean deleteDoc(List<DocumentDTO> listDoc) {
		for(DocumentDTO doc : listDoc ) {
			deleteDoc(doc.getId());
		}
		return true;
	}
}
